#!/bin/bash

resultsFileName='testResults.out';
testData='exprComparisonTests.dat';
outputData='exprComparisonTestResults.dat';
testBaseLine='exprComparisonTestsBaseLine.dat';
testScript='exprComparisonTests.qg';

cat $testData | awk ' 
BEGIN { FS=";" 
  counter=0;
# generate script header
  printf("SCRIPT {\n");
  printf("\n");
  printf("\tDECLARE bool var_bool;\n");
};


{
  counter++;
  printf("// Test #%i\n", counter);
  if(substr($0, 1, 1) == "#")
  {
    printf("Ignoring test #%i because it is preceeded by a # character.\n", counter) > "/dev/stderr";
    printf("// Ignored test #%i because it is preceeded by a # character.\n", counter);
  }else{
    if(NF >= 3){
      baseline="true";
    }else{
      printf("Error in test data file. Missing data for test %i.\n", counter) > "/dev/stderr";
    }
    printf("\tvar_bool= ( %s %s %s );\n", $1, $2, $3);
    printf("\tprint(var_bool);\n");
    printf("\tprint(%s);\n", baseline);
  }
  printf("\n");
}

END {
  printf("}\n");
}
' > $testScript


for BIN in ./main_dbg ./main_opt; do
 echo -------------------------------------
 echo Compiling tests for ${BIN}.
 $BIN -namelist $testScript -compile
 if [ "$?" != "0" ]; then
  echo "Error compiling tests." > /dev/stderr;
  exit 1;
 fi
 echo Finished compiling tests.
 $BIN -runscript $testScript > $outputData;
 cat $outputData | awk 'BEGIN {swtch = 0; counter = 0; result=0; status=1;} 
{
  if(swtch == 0){
    result=$1;
    swtch=1;
  }else{
    counter++;
    if( result!=$1 ){
      status = 0;
      printf("Failed test %i.\n", counter) > "/dev/stderr";
      printf("\tExpected: %s\n", $1) > "/dev/stderr";
      printf("\tEvaluation returned: %s\n", result) > "/dev/stderr";
    }
    swtch=0;
  }
}

END {
  if(status == 1 ){
    exit(0);
  }else{
    exit(1);
  }
}'

 if [ "$?" == "0" ]; then
  echo All tests in suite passed for $BIN. > /dev/stderr;
 else
  echo Some tests failed for $BIN. > /dev/stderr;
 fi
done
